<script setup>
import { reactive, ref } from "vue";
import { modifyApi } from "@/api/user";
import { useUserStore } from "@/store/user";
import { getUserInfo } from "@/utils";
import { ElMessage } from "element-plus";
const userStore = useUserStore();

const formRef = ref();

const form = reactive({
  username: getUserInfo().username || "",
});

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate();
  const user_id = getUserInfo().user_id;
  const res = await modifyApi({ ...form, user_id });
  if (res.data.status === 200) {
    ElMessage({
      message: "用户名修改成功",
      type: "success",
    });
    userStore.setUserInfo({ user_id, username: form.username });
    sessionStorage.setItem(
      "userInfo",
      JSON.stringify({ user_id, username: form.username })
    );
  } else {
    ElMessage({
      message: res.data.message,
      type: "error",
    });
  }
};

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
<template>
  <div>
    <el-form ref="formRef" :model="form" label-width="100px">
      <el-form-item
        label="用户名"
        prop="username"
        :rules="[{ required: true, message: '请填写用户名' }]"
      >
        <el-input v-model="form.username" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style lang="scss" scoped></style>
